import React, { useState } from 'react';
import { Form, Input, message, Modal, Row } from 'antd';
import { GlobalFormLayout } from '@/layouts/Form';
import request from '@/utils/request';

const { Password } = Input;

function AddUserModal({ data = {}, visible, onCancel, form }) {
  const { getFieldDecorator, validateFields } = form;
  const [loading, setLoading] = useState(false);

  const handleSubmit = () => {
    validateFields((err, values) => {
      if (!err) {
        const { password, confirmedPassword, username } = values;
        if (password !== confirmedPassword) {
          message.error('两次输入的密码不一致');
          return;
        }
        setLoading(true);
        request
          .post('/user/create', {
            data: {
              username,
              password,
            },
          })
          .then(() => {
            message.success('创建成功');
            onCancel();
          })
          .finally(() => setLoading(false));
      }
    });
  };

  return (
    <Modal
      title="新增用户"
      onOk={handleSubmit}
      okButtonProps={{ loading }}
      visible={visible}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form {...GlobalFormLayout}>
        <Form.Item label="用户名">
          {getFieldDecorator('username', {
            rules: [
              {
                required: true,
                message: '用户名不能为空',
              },
            ],
          })(<Input placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item label="密码">
          {getFieldDecorator('password', {
            rules: [
              {
                required: true,
                message: '密码不能为空',
              },
            ],
          })(<Password placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item label="确认密码">
          {getFieldDecorator('confirmedPassword', {
            rules: [
              {
                required: true,
                message: '确认密码不能为空',
              },
            ],
          })(<Password placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default Form.create()(AddUserModal);
